<?php
declare (strict_types = 1);

namespace app\product\service;

use app\product\model\SupplierModel;
use think\facade\Validate;

class SupplierService extends BaseService
{
    public function __construct(SupplierModel $supplierModel)
    {
        $this->supplierModel = $supplierModel;
    }

    public function model(){
        return $this->supplierModel;
    }

    public function list(array $where = [] , array $limit = [], array $sort= []){
        $limit = check_limit($limit);
        $sort = check_sort($sort);
        return $this->supplierModel::with([SupplierModel::WITH_PROVINCE,SupplierModel::WITH_CITY,SupplierModel::WITH_AREA])->where($where)->limit($limit['page'],$limit['pagesize'])->order($sort[0],$sort[1])->select();
    }

    public function select(array $where = [],$field = ['*']){
        return $this->supplierModel->field($field)->where($where)->select();
    }

    public function count(array $where = [],array $whereIn = []){
        $model = $this->supplierModel;
        $model = $model->where($where);
        if(!empty($whereIn)) $model = $model->whereIn($whereIn[0],$whereIn[1]);
        return $model->count();
    }

    public function find(array $where = []){
        return $this->supplierModel->where($where)->find();
    }

    public function value(array $where = [], string $column = ''){
        return $this->supplierModel->where($where)->value($column);
    }

    public function insertGetId(array $data = []){
        return $this->supplierModel->insertGetId($data);
    }

    public function insertAll(array $data = []){
        return $this->supplierModel->insertAll($data);
    }

    public function update(array $where = [],array $data = []){
        return $this->supplierModel->where($where)->update($data);
    }

    public function delete(array $whereIn = []){
        return $this->supplierModel->whereIn($whereIn[0],$whereIn[1])->delete();
    }

    public function verify(array $params = [],int $id = 0){
        $tableName = $this->model()->getTable();
        $validate = Validate::rule([
            'name'=>'require|chsDash|unique:'.$tableName.',name,'.$id,
            'url' => 'require',
        ]);
        if(!$validate->check($params)) return $validate->getError();
        $data = array();
        $data['name'] = $params['name'];
        $data['url'] = $params['url'];
        $data['province_code'] = intval($params['province_code'])??0;
        $data['city_code'] = intval($params['city_code'])??0;
        $data['area_code'] = intval($params['area_code'])??0;
        if(empty($id)) {
            $data['create_time'] = time();
        }else{
            $data['update_time'] = time();
        }
        return $data;
    }
}
